﻿
//
// 版权所有 (c) 2021-2023 JR
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using Nest;
using System.Linq;

namespace EMC.VISITOR.Core.Service;

/// <summary>
/// 系统代码生成配置服务
/// </summary>
[ApiDescriptionSettings(Order = 260)]
public class SysOtherSystemMapperGenConfigService : IDynamicApiController, ITransient
{
    private readonly ISqlSugarClient _db;
    private readonly CodeGenOptions _codeGenOptions;
    private readonly SysDatabaseService _sysDatabaseService;

    public SysOtherSystemMapperGenConfigService(ISqlSugarClient db, IOptions<CodeGenOptions> codeGenOptions, SysDatabaseService sysDatabaseService)
    {
        _db = db;
        _codeGenOptions = codeGenOptions.Value;
        _sysDatabaseService = sysDatabaseService;
    }

    /// <summary>
    /// 获取代码生成配置列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取代码生成配置列表")]
    public async Task<List<SysOtherSystemMapperGenConfig>> GetList([FromQuery] CodeGenConfig input)
    {
        var res = await _db.Queryable<SysOtherSystemMapperGenConfig>()
            .Where(u => u.CodeGenId == input.CodeGenId && u.WhetherCommon != YesNoEnum.Y.ToString())
            .Select<SysOtherSystemMapperGenConfig>()
            .Mapper(u =>
            {
                u.NetType = (u.EffectType == "EnumSelector" || u.EffectType == "ConstSelector" ? u.DictTypeCode : u.NetType);
            })
            .OrderBy(u => u.OrderNo)
            .ToListAsync();

        return res;
    }
    [ApiDescriptionSettings(Name = "GetCurrentAssemblyNames"), HttpGet]
    [DisplayName("获取当前项目所有程序集名称")]
    public async Task<List<string>> GetCurrentAssemblyNames()
    {
        await Task.CompletedTask;
        return _codeGenOptions.EntityAssemblyNames;

    }
    /// <summary>
    /// 更新代码生成配置
    /// </summary>
    /// <param name="inputList"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    [DisplayName("更新代码生成配置")]
    public async Task UpdateCodeGenConfig(List<CodeGenConfig> inputList)
    {
        if (inputList == null || inputList.Count < 1) return;
        if (inputList.Any(r => r.PropertyName.IsNullOrEmpty() || r.OtherSystemColumnName.IsNullOrEmpty()))
            throw Oops.Oh(ErrorCodeEnum.D1502);

        var list = inputList.Adapt<List<SysOtherSystemMapperGenConfig>>();

        list.ForEach(r =>
        {
            r.ColumnName = r.PropertyName;
        });

        var updateList = list.Where(r => r.Id > 0).ToList();
        var insertList = list.Where(r => r.Id <= 0).ToList();

        if (updateList.Count > 0)
            await _db.Updateable(updateList)
                .ExecuteCommandAsync();

        if (insertList.Count > 0)
            await _db.Insertable(insertList).ExecuteCommandAsync();

        //var MapperGen = await _db.Queryable<SysOtherSystemMapperGen>().FirstAsync(r => r.Id == inputList.FirstOrDefault().CodeGenId);
        //if (MapperGen != null)
        //{
        //    //更新数据库
        //    _sysDatabaseService.OneTableChange(MapperGen.TableName + MapperGen.Temp2);
        //}
    }

    /// <summary>
    /// 删除代码生成配置
    /// </summary>
    /// <param name="codeGenId"></param>
    /// <returns></returns>
    [NonAction]
    public async Task DeleteCodeGenConfig(long codeGenId)
    {
        await _db.Deleteable<SysOtherSystemMapperGenConfig>().Where(u => u.CodeGenId == codeGenId).ExecuteCommandAsync();
    }

    [NonAction]
    public async Task DeleteCodeGenConfigs(List<SysOtherSystemMapperGenConfig> configs)
    {
        await _db.Deleteable<SysOtherSystemMapperGenConfig>(configs).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取代码生成配置详情
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取代码生成配置详情")]
    public async Task<SysOtherSystemMapperGenConfig> GetDetail([FromQuery] CodeGenConfig input)
    {
        return await _db.Queryable<SysOtherSystemMapperGenConfig>().FirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 批量增加代码生成配置
    /// </summary>
    /// <param name="tableColumnOuputList"></param>
    /// <param name="codeGenerate"></param>
    [NonAction]
    public void AddList(List<ColumnOuput> tableColumnOuputList, SysOtherSystemMapperGen codeGenerate)
    {
        if (tableColumnOuputList == null) return;

        var codeGenConfigs = new List<SysOtherSystemMapperGenConfig>();
        var orderNo = 100;
        foreach (var tableColumn in tableColumnOuputList)
        {
            var codeGenConfig = new SysOtherSystemMapperGenConfig();

            var YesOrNo = YesNoEnum.Y.ToString();
            if (Convert.ToBoolean(tableColumn.ColumnKey))
            {
                YesOrNo = YesNoEnum.N.ToString();
            }

            if (CodeGenUtil.IsCommonColumn(tableColumn.ColumnName))
            {
                codeGenConfig.WhetherCommon = YesNoEnum.Y.ToString();
                YesOrNo = YesNoEnum.N.ToString();
            }
            else
            {
                codeGenConfig.WhetherCommon = YesNoEnum.N.ToString();
            }

            codeGenConfig.CodeGenId = codeGenerate.Id;
            codeGenConfig.ColumnName = tableColumn.ColumnName; // 字段名
            codeGenConfig.PropertyName = tableColumn.PropertyName;// 实体属性名
            codeGenConfig.ColumnLength = tableColumn.ColumnLength;// 长度
            codeGenConfig.ColumnComment = tableColumn.ColumnComment;
            codeGenConfig.NetType = tableColumn.DataType;
            codeGenConfig.WhetherRetract = YesNoEnum.N.ToString();
            codeGenConfig.OtherSystemColumnName = tableColumn.ColumnName;
            codeGenConfig.OtherSystemColumnType = tableColumn.DataType;
            // 生成代码时，主键并不是必要输入项，故一定要排除主键字段
            codeGenConfig.WhetherRequired = (tableColumn.IsNullable || tableColumn.IsPrimarykey) ? YesNoEnum.N.ToString() : YesNoEnum.Y.ToString();
            codeGenConfig.QueryWhether = YesOrNo;
            codeGenConfig.WhetherAddUpdate = YesOrNo;
            codeGenConfig.WhetherTable = YesOrNo;

            codeGenConfig.ColumnKey = tableColumn.ColumnKey;

            codeGenConfig.DataType = tableColumn.DataType;
            codeGenConfig.EffectType = CodeGenUtil.DataTypeToEff(codeGenConfig.NetType);
            codeGenConfig.QueryType = GetDefaultQueryType(codeGenConfig); // QueryTypeEnum.eq.ToString();
            codeGenConfig.OrderNo = orderNo;
            codeGenConfigs.Add(codeGenConfig);

            orderNo += 10; // 每个配置排序间隔10
        }
        // 多库代码生成---这里要切回主库
        var provider = _db.AsTenant().GetConnectionScope(SqlSugarConst.MainConfigId);
        provider.Insertable(codeGenConfigs).ExecuteCommand();
    }

    /// <summary>
    /// 默认查询类型
    /// </summary>
    /// <param name="codeGenConfig"></param>
    /// <returns></returns>
    private string GetDefaultQueryType(SysOtherSystemMapperGenConfig codeGenConfig)
    {
        return (codeGenConfig.NetType?.TrimEnd('?')) switch
        {
            "string" => "like",
            "DateTime" => "~",
            _ => "==",
        };
    }
}